#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
from aredis import StrictRedis

from lib.conf.config import settings
from src import PluginManager
from utils.url_md5 import str_md5


class ResponseValue:

    def __init__(self, url, params, body, files):
        self.params = params
        self.body = body
        self.files = files
        self.url = url

    def __str__(self):
        return 'url:{}'.format(self.url)


async def main(url):
    conn = StrictRedis(host=settings.HOST, port=settings.PORT, db=settings.DB)
    str_ = '{0}{1}'.format(settings.BASE_URL, url)
    key = await str_md5(str_)
    while True:
        value = await conn.brpop(key)
        value_dict_md5 = value[1].decode('utf-8')
        redis_key_dict = settings.MOD.format(key)
        status = await conn.hexists(redis_key_dict, value_dict_md5)
        print('status', status)
        if status:
            value_dict_json = await conn.hget(redis_key_dict, value_dict_md5)
            await conn.hdel(redis_key_dict, value_dict_md5)
            redis_value = json.loads(value_dict_json.decode('utf-8'))
            plug = PluginManager()
            res = ResponseValue(url=url, params=redis_value.get('params'),
                               body=redis_value.get('body'),
                               files=redis_value.get('files'))
            plug.value = res
            plug.key = key
            await plug.exec_plugin()
            del res, plug
